package com.ldc.common.utils;

import android.app.Activity;
import android.util.Log;

import java.util.LinkedList;

public class ActivityUtils {
    private static final String TAG = "ActivityUtils";

    private static final LinkedList<Activity> activityLinkedList = new LinkedList<>();


    public static void addActivity(Activity activity) {
        activityLinkedList.add(activity);
    }


    public static void remove(Activity activity) {
        if (null == activity || activityLinkedList.contains(activity)) {
            return;
        }
        activityLinkedList.remove(activity);
    }

    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        if (activityLinkedList.isEmpty()) {
            return null;
        }
        return activityLinkedList.get(activityLinkedList.size() - 1);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (activityLinkedList.isEmpty()) {
            return;
        }
        if (activity != null) {
            activityLinkedList.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        if (activityLinkedList.isEmpty()) {
            return;
        }
        for (Activity activity : activityLinkedList) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public static Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (activityLinkedList) {
            final int size = activityLinkedList.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = activityLinkedList.get(size);
        }
        return mBaseActivity;
    }

    public static String getTopActivityName() {
        Activity activity = getTopActivity();
        if (activity == null) {
            return null;
        }
        return activity.getClass().getName();
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        for (Activity activity : activityLinkedList) {
            activity.finish();
        }
        activityLinkedList.clear();
    }

    /**
     * 退出应用程序
     */
    public static void appExit() {
        try {
            finishAllActivity();
        } catch (Exception e) {
            Log.i(TAG, "appExit: " + e.getMessage());
        }
    }
}
